package com.xinhe.web.controller;

import com.xinhe.web.common.Result;
import com.xinhe.web.response.AttachView;
import com.xinhe.web.service.AttachService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

@Api(value = "附件", tags = {"附件"})
@RestController
@RequestMapping(value = {"/attach"}, produces = {"application/json;charset=UTF-8"})
public class AttachController {
    private static final String UPLOAD_DIR = File.separator + "upload";
    public static final String UNDER_LINE = "_";

    @Autowired
    private AttachService attachService;

    /*@Autowired
    private IValueConfigCache valueConfigCache;*/

    @ApiOperation(httpMethod = "GET", value = "查询附件")
    @RequestMapping({"/findByBusinessIdAndType"})
    public Result<List<AttachView>> findByBusinessIdAndType(Long businessId, String type) {
        return this.attachService.findByBusinessIdAndType(businessId, type);
    }

    /*@ApiOperation(httpMethod = "GET", value = "分页查询附件")
    @RequestMapping({"/pageAttach"})
    public PageResult<AttachView> pageAttach(@RequestBody AttachQuery query) {
        return this.attachService.pageAttach(query);
    }


    @ApiOperation(httpMethod = "GET", value = "附件详情")
    @ApiImplicitParam(name = "attachId", value = "标识", dataTypeClass = Long.class, required = true)
    @RequestMapping({"/detailAttach"})
    public BeanResult<Attach> detailAttach(Long attachId) {
        return this.attachService.findById(attachId);
    }

    @ApiOperation(httpMethod = "GET", value = "查询附件")
    @RequestMapping({"/findByBusinessId"})
    public ListResult<AttachView> findByBusinessId(Long businessId) {
        return this.attachService.findByBusinessId(businessId);
    }
    @RequestMapping({"/upload"})
    public BeanResult<UploadView> upload(UploadModel model) {
        BeanResult<UploadView> result = new BeanResult();
        MultipartFile file = model.getFile();
        String path = uploadFile(file, model.getFolder(), model.getFileNamePre());
        BeanResult<AttachView> attachResult = this.attachService.saveAttachTemp(new AttachTempModel(path, file.getOriginalFilename(), file.getContentType(), model.getFileNamePre()));
        if (attachResult.getSuccess().booleanValue()) {
            AttachView attach = (AttachView)attachResult.getItem();
            UploadView view = new UploadView();
            view.setAttachId(attach.getId());
            view.setPath(path);
            view.setName(attach.getName());
            result.setItem(view);
            result.setMsg(path);
        } else {
            attachResult.convertTo((BaseResult)result);
        }
        return result;
    }

    private String uploadFile(MultipartFile file, String folder, String fileNamePre) {
        UploadFolder uploadFolder = getUploadDir(folder);
        String sourceName = file.getOriginalFilename();
        String suffix = sourceName.substring(sourceName.lastIndexOf("."));
        String dataTime = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
        Double random = Double.valueOf(Math.random() * 10000.0D);
        String fileName = fileNamePre + "_" + dataTime + "_" + random.intValue() + suffix;
        File targetFile = new File(uploadFolder.getFile(), fileName);
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
        return uploadFolder.getPath() + File.separator + fileName;
    }

    private UploadFolder getUploadDir(String folder) {
        String dirPath = null;
        String relativePath = UPLOAD_DIR;
        if (StringUtils.isNotBlank(folder)) {
            relativePath = relativePath + File.separator + folder;
        }
        ValueConfigView resourceHomeConfig = this.valueConfigCache.get("resource-home");
        if (null != resourceHomeConfig) {
            dirPath = resourceHomeConfig.getValue() + relativePath;
        }
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            boolean mkResult = dirFile.mkdirs();
            if (!mkResult) {
                LOGGER.error("附件目录创建失败");
            }
        }
        UploadFolder fileFolder = new UploadFolder();
        fileFolder.setFile(dirFile);
        fileFolder.setPath(relativePath);
        return fileFolder;
    }

    static class UploadFolder
    {
        private File file;

        private String path;

        public File getFile() {
            return this.file;
        }





        public void setFile(File file) {
            this.file = file;
        }




        public String getPath() {
            return this.path;
        }





        public void setPath(String path) {
            this.path = path;
        }
    }*/
}
